const {app, Menu, ipcMain, dialog, BrowserWindow} = require('electron');

const WinState = require('electron-win-state').default

const path = require('path')

const createTray = require('./components/Tray')

const mainMenu = require('./components/MainMenu')

const icon = path.join(__dirname, 'icons', 'icon.ico')

const createWindow = () => {
    const winState = new WinState({
        defaultWidth: 1000,
        defaultHeight: 600,
        electronStoreOptions: {
            name: 'main-window-state'
        }
    });

    let window = new BrowserWindow({
            ...winState.winOptions,
            // x: 100, //窗口显示 x 轴坐标
            // y: 100, //窗口显示 y 轴坐标
            minWidth: 500, //窗口最小宽度
            minHeight: 300, //窗口最高度宽度
            // title: '标题', //窗口标题
            // frame: false, // 隐藏默认菜单栏、关闭窗口、隐藏窗口、展开窗口等
            // frame: true, autoHideMenuBar: true, //隐藏默认菜单栏
            // 窗口显示图标
            icon: icon,
            //关闭创建窗
            // 口对象之后就立即显示窗口（窗口未加载完成，从而显示空白窗口）
            show: true,
            title: '幸运大转盘',
            //是否允许窗口缩放
            resizable: true,
            webPreferences:
                {
                    nodeIntegration: true,
                    contextIsolation: true,
                    preload: path.join(__dirname, 'preload', 'index.js'),
                }
        });

    window.loadURL(`file://${path.join(__dirname, 'table-mode.html')}`)

    createTray(app, window)

    Menu.setApplicationMenu(mainMenu({window}))

    winState.manage(window)

    // 打开开发者工具（调试窗口）
    // window.webContents.openDevTools()

    window.on('ready-to-show', () => {
        window.show()

    })

    /**
     * 窗口关闭触发
     */
    window.on('close', () => {
        window = null
    })
}


/**
 * 完成初始化后触发
 */
app.whenReady().then(() => {
    createWindow()
    app.on('activate', () => {
        if (BrowserWindow.getAllWindows().length === 0) {
            createWindow()
        }
    })
})

/**
 * 所有窗口都关闭时触发
 */
app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

ipcMain.on('messageBox-event', (event, args) => {
    dialog.showMessageBox({
        type: 'info',
        title: '抽取结果',
        message: `恭喜您抽中了：${args}`,
        buttons: ['确认']
    }).then(res => {

    })
})
